<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能客服系统</title>
    <!-- 添加 Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
        }
        
        body {
            background-color: #f5f5f5;
            display: flex;
            flex-direction: column;
            height: 100vh;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            display: flex;
            flex: 1;
            gap: 20px;
        }
        
        .sidebar {
            width: 300px;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 15px;
            display: flex;
            flex-direction: column;
        }
        
        .main-content {
            flex-grow: 1;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
        }
        
        .header {
            background-color: #1890ff;
            color: white;
            padding: 15px 20px;
            border-radius: 10px 10px 0 0;
        }
        
        .chat-container {
            flex-grow: 1;
            padding: 20px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        
        .message {
            max-width: 80%;
            padding: 10px 15px;
            border-radius: 15px;
            position: relative;
            word-break: break-word;
        }
        
        .user-message {
            align-self: flex-end;
            background-color: #e6f7ff;
            color: #333;
            border-bottom-right-radius: 0;
        }
        
        .assistant-message {
            align-self: flex-start;
            background-color: #f1f1f1;
            color: #333;
            border-bottom-left-radius: 0;
        }
        
        .message-input {
            display: flex;
            padding: 15px;
            border-top: 1px solid #eee;
        }
        
        input[type="text"] {
            flex-grow: 1;
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 25px;
            outline: none;
            font-size: 14px;
        }
        
        button {
            background-color: #1890ff;
            color: white;
            border: none;
            border-radius: 25px;
            padding: 10px 20px;
            margin-left: 10px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }
        
        button:hover {
            background-color: #40a9ff;
        }
        
        button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        
        .session-list {
            flex-grow: 1;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-bottom: 15px;
        }
        
        .session-item {
            padding: 10px;
            background-color: #f5f5f5;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        .session-item:hover, .session-item.active {
            background-color: #e6f7ff;
        }
        
        .model-selector {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }
        
        .model-option {
            flex: 1;
            text-align: center;
            padding: 8px;
            background-color: #f5f5f5;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        .model-option:hover, .model-option.active {
            background-color: #e6f7ff;
        }

        .timestamp {
            font-size: 10px;
            color: #999;
            margin-top: 5px;
        }
        
        /* 添加模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }
        
        .modal.show {
            display: block;
        }
        
        .review-button {
            font-size: 12px;
            padding: 2px 8px;
            margin-left: 10px;
            background-color: #52c41a;
        }
        
        .review-button:hover {
            background-color: #73d13d;
        }
        
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 10px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="sidebar">
            <h2 style="margin-bottom: 15px;">会话列表</h2>
            <div class="model-selector">
                <div class="model-option active" data-model="deepseek">DeepSeek</div>
                <div class="model-option" data-model="qwen">通义千问</div>
            </div>
            <div class="session-list" id="sessionList">
                <!-- 会话项动态生成 -->
            </div>
            <button id="newSessionBtn">新建会话</button>
        </div>
        
        <div class="main-content">
            <div class="header">
                <h2>智能客服助手</h2>
            </div>
            <div class="chat-container" id="chatContainer">
                <!-- 消息内容动态生成 -->
                <div class="message assistant-message">
                    您好！我是智能客服助手，请问有什么可以帮助您的吗？
                    <div class="timestamp">刚刚</div>
                </div>
            </div>
            <div class="message-input">
                <input type="text" id="messageInput" placeholder="请输入您的问题...">
                <button id="sendBtn">发送</button>
            </div>
        </div>
    </div>

    <!-- 添加人工审核模态框 -->
    <div class="modal fade" id="humanReviewModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">人工审核</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">AI原始回答</label>
                        <div class="original-response p-3 bg-light rounded"></div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">修改后的回答</label>
                        <textarea class="form-control modified-response" rows="5"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">操作类型</label>
                        <select class="form-select operation-type">
                            <option value="EDIT">编辑</option>
                            <option value="SUPPLEMENT">补充</option>
                            <option value="REWRITE">重写</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">质量评级</label>
                        <select class="form-select quality-rating">
                            <option value="GOOD">好</option>
                            <option value="MEDIUM">中</option>
                            <option value="POOR">差</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">备注说明</label>
                        <textarea class="form-control remarks" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary save-intervention">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加 Bootstrap JS 和依赖 -->
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js"></script>
    
    <script>
        // 全局变量
        let currentSessionId = null;
        let selectedModel = 'deepseek';
        let isProcessing = false;
        
        // DOM 元素
        const sessionList = document.getElementById('sessionList');
        const chatContainer = document.getElementById('chatContainer');
        const messageInput = document.getElementById('messageInput');
        const sendBtn = document.getElementById('sendBtn');
        const newSessionBtn = document.getElementById('newSessionBtn');
        const modelOptions = document.querySelectorAll('.model-option');
        
        // 人工审核相关变量
        let currentMessageId = null;
        const humanReviewModal = new bootstrap.Modal(document.getElementById('humanReviewModal'));
        
        // 初始化页面
        document.addEventListener('DOMContentLoaded', () => {
            // 创建新会话
            createNewSession();
            
            // 监听发送按钮点击
            sendBtn.addEventListener('click', () => {
                if (!isProcessing && messageInput.value.trim()) {
                    sendMessage();
                }
            });
            
            // 监听输入框回车
            messageInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter' && !e.shiftKey && !isProcessing && messageInput.value.trim()) {
                    e.preventDefault();
                    sendMessage();
                }
            });
            
            // 监听新建会话按钮点击
            newSessionBtn.addEventListener('click', () => {
                if (!isProcessing) {
                    createNewSession();
                }
            });
            
            // 监听模型选择
            modelOptions.forEach(option => {
                option.addEventListener('click', () => {
                    if (!isProcessing) {
                        modelOptions.forEach(o => o.classList.remove('active'));
                        option.classList.add('active');
                        selectedModel = option.dataset.model;
                    }
                });
            });
            
            // 初始化人工审核功能
            initHumanReview();
            
            // 绑定保存按钮事件
            document.querySelector('.save-intervention').onclick = saveHumanIntervention;
        });
        
        // 发送消息
        async function sendMessage() {
            const message = messageInput.value.trim();
            if (!message) return;
            
            messageInput.value = '';
            isProcessing = true;
            sendBtn.disabled = true;
            
            // 添加用户消息到界面
            appendMessage(message, 'user');
            
            try {
                const response = await fetch('/api/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        sessionId: currentSessionId,
                        message: message,
                        modelType: selectedModel
                    })
                });
                
                if (!response.ok) {
                    throw new Error('网络请求失败');
                }
                
                const data = await response.json();
                appendMessage(data.message, 'assistant');
                
            } catch (error) {
                console.error('发送消息失败:', error);
                appendMessage('抱歉，服务出现错误，请稍后重试。', 'assistant');
            } finally {
                isProcessing = false;
                sendBtn.disabled = false;
            }
        }
        
        // 添加消息到聊天窗口
        function appendMessage(content, role) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}-message`;
            
            const messageContent = document.createElement('div');
            messageContent.textContent = content;
            messageDiv.appendChild(messageContent);
            
            const timestamp = document.createElement('div');
            timestamp.className = 'timestamp';
            timestamp.textContent = new Date().toLocaleTimeString();
            messageDiv.appendChild(timestamp);
            
            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
        
        // 创建新会话
        function createNewSession() {
            currentSessionId = generateUUID();
            
            // 清空聊天记录
            chatContainer.innerHTML = '';
            appendMessage('您好！我是智能客服助手，请问有什么可以帮助您的吗？', 'assistant');
            
            // 创建会话项
            const sessionItem = document.createElement('div');
            sessionItem.className = 'session-item active';
            sessionItem.textContent = `会话 ${new Date().toLocaleTimeString()}`;
            sessionItem.dataset.id = currentSessionId;
            
            // 移除其他会话的active状态
            document.querySelectorAll('.session-item').forEach(item => {
                item.classList.remove('active');
            });
            
            // 添加到会话列表
            if (sessionList.firstChild) {
                sessionList.insertBefore(sessionItem, sessionList.firstChild);
            } else {
                sessionList.appendChild(sessionItem);
            }
            
            // 绑定会话点击事件
            sessionItem.addEventListener('click', () => {
                if (!isProcessing) {
                    document.querySelectorAll('.session-item').forEach(item => {
                        item.classList.remove('active');
                    });
                    sessionItem.classList.add('active');
                    currentSessionId = sessionItem.dataset.id;
                }
            });
        }
        
        // 显示人工审核按钮
        function showHumanReviewButton(messageElement) {
            const actionsDiv = messageElement.querySelector('.message-actions');
            const reviewBtn = actionsDiv.querySelector('.human-review-btn');
            reviewBtn.style.display = 'inline-block';
        }
        
        // 初始化人工审核功能
        function initHumanReview() {
            // 为所有AI消息添加人工审核按钮
            document.querySelectorAll('.message.assistant').forEach(message => {
                const actionsDiv = message.querySelector('.message-actions');
                if (!actionsDiv.querySelector('.human-review-btn')) {
                    const reviewBtn = document.createElement('button');
                    reviewBtn.className = 'btn btn-sm btn-outline-primary human-review-btn';
                    reviewBtn.innerHTML = '<i class="bi bi-pencil"></i> 人工审核';
                    reviewBtn.onclick = () => openHumanReview(message);
                    actionsDiv.appendChild(reviewBtn);
                }
                showHumanReviewButton(message);
            });
        }
        
        // 打开人工审核模态框
        function openHumanReview(messageElement) {
            currentMessageId = messageElement.dataset.messageId;
            currentSessionId = messageElement.dataset.sessionId;
            
            const originalResponse = messageElement.querySelector('.message-text').textContent;
            document.querySelector('.original-response').textContent = originalResponse;
            document.querySelector('.modified-response').value = originalResponse;
            
            humanReviewModal.show();
        }
        
        // 保存人工干预
        async function saveHumanIntervention() {
            const intervention = {
                sessionId: currentSessionId,
                messageId: currentMessageId,
                originalAiResponse: document.querySelector('.original-response').textContent,
                modifiedResponse: document.querySelector('.modified-response').value,
                operationType: document.querySelector('.operation-type').value,
                qualityRating: document.querySelector('.quality-rating').value,
                remarks: document.querySelector('.remarks').value,
                operatorId: 'admin' // 实际项目中应该使用真实的用户ID
            };
            
            try {
                const response = await fetch('/api/interventions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(intervention)
                });
                
                if (response.ok) {
                    // 更新消息内容
                    const messageElement = document.querySelector(`[data-message-id="${currentMessageId}"]`);
                    messageElement.querySelector('.message-text').textContent = intervention.modifiedResponse;
                    
                    // 关闭模态框
                    humanReviewModal.hide();
                    
                    // 显示成功提示
                    showToast('人工审核已保存');
                } else {
                    throw new Error('保存失败');
                }
            } catch (error) {
                console.error('保存人工干预失败:', error);
                showToast('保存失败，请重试', 'error');
            }
        }
        
        // 生成UUID
        function generateUUID() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                const r = Math.random() * 16 | 0;
                const v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }
    </script>
</body>
</html> 